<template>
  <div>
    <el-dialog v-model="dialog.visible" :title="dialog.title" @close="hide()">
      <div class="content">
        <!-- <div class="flex items-center type" v-if="type === 'BYTE_APP'">
          <div
            class="bg-[#f1f1f1] px-[8px] py-[4px] rounded-[4px] mr-[4px] cursor-pointer text-[12px] items"
            :class="curType === 0 ? 'active' : ''"
            @click="handleCurType(0)"
          >
            全账户复用
          </div>
          <div
            class="bg-[#f1f1f1] px-[8px] py-[4px] rounded-[4px] mr-[4px] cursor-pointer text-[12px] items"
            :class="curType === 1 ? 'active' : ''"
            @click="handleCurType(1)"
          >
            按账户分配
          </div>
        </div> -->
        <div class="flex items-start mt-[20px] left">
          <div class="w-[200px] border-solid border-1px border-[#dcdfe6] h-[533px] mr-[10px] overflow-y-scroll userlist" v-if="curType === 1">
            <div
              class="flex items-center justify-between px-[15px] py-[8px] cursor-pointer userItem"
              v-for="(item, index) in userList"
              :key="index"
              :class="curAdvertiserIndex === index ? 'bg-[#ECF5FF]' : ''"
              @click="selectUser(index)"
            >
              <div class="text-cut info">
                <div class="text-cut name">{{ item.name }}</div>
                <div class="text-cut mt-[3px] text-[12px] text-[#ccc] id">ID:{{ item.id }}</div>
              </div>
              <div class="shrink-0 action">
                <el-icon v-if="item.appId" color="#197AFB"><SuccessFilled /></el-icon>
                <el-icon v-else><CircleCheck /></el-icon>
              </div>
            </div>
          </div>
          <div class="flex flex-col productlist">
            <div class="flex items-center justify-between searchbox">
              <div class="flex items-center">
                <el-input v-model="keywords" placeholder="请输入关键词" clearable @clear="clearSearch" />
                <el-button class="ml-[15px]" @click="toSearch">查询</el-button>
              </div>
              <div class="btnbox">
                <el-button type="primary" class="ml-[15px]" :loading="loading" @click="getMircoAppList">同步</el-button>
              </div>
            </div>
            <div class="pt-[15px] flex">
              <div class="w-[500px] border-solid border-1px border-[#dcdfe6] shrink-0 contlist">
                <div class="h-[484px] cont">
                  <el-table
                    class="myTable"
                    height="440"
                    ref="tableRef"
                    :data="productList"
                    row-key="appId"
                    @select="handleSelectionChange"
                    v-loading="loading"
                    style="font-size: 12px"
                    @row-click="handelRowClick"
                  >
                    <el-table-column type="selection" width="55" />
                    <el-table-column property="name" width="90" label="名称" />
                    <el-table-column property="instanceId" label="小程序资产" />
                    <el-table-column property="remark" label="备注">
                      <template #default="{ row }">
                        {{ props.type === 'WECHAT_APP' ? row.remarkMessage : row.remark }}
                      </template>
                    </el-table-column>
                  </el-table>
                  <pagination
                    size="small"
                    v-show="total > 0"
                    :total="total"
                    layout=" prev, pager, next"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getMircoAppList"
                  />
                </div>
              </div>
              <div class="text-[14px] ml-[10px] h-[484px] w-[200px] selectlist">
                <div class="flex justify-between items-center border-solid border-1px px-[15px] py-[4px] border-[#dcdfe6] selectAcout">
                  <div class="numtxt">已选({{ selectRows[curAdvertiserIndex] ? selectRows[curAdvertiserIndex].length : 0 }}/1)</div>
                  <div
                    class="cursor-pointer action"
                    :class="selectRows[curAdvertiserIndex].length ? 'text-[#297bfb]' : 'text-[#a9c5f1]'"
                    @click="clearAll"
                  >
                    清空
                  </div>
                </div>
                <div class="h-[455px] border-solid border-1px border-[#dcdfe6] border-t-0 listbox">
                  <div
                    class="flex justify-between items-center px-[15px] py-[8px] bg-[#fafafa] cursor-pointer item"
                    v-for="(item, index) in selectResult[curAdvertiserIndex]"
                    :key="index"
                  >
                    <div class="text">
                      {{ item.appName }}
                    </div>
                    <div class="cursor-pointer action" @click="clearAll">
                      <el-icon><Close /></el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button plain @click="hide()">取消</el-button>
        <el-button type="primary" plain @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  byteMircroAppList,
  wechatMircroAppList,
  queryToolsMicroAppNew,
  getAllWechatApplet,
  type MicroAppQuery,
  type ByteMicroAppItem,
  type WechatMircroAppItem,
  type ByteMicroAppVO,
  type WechatMicroAppVO
} from '@/api/com';
import { getEventAllAssetsList } from '@/api/advertisement/eventAssets';
import { EventAssetsVo, EventAssetsQuery, EventManagerConfigsVo } from '@/api/advertisement/eventAssets/types';
import { useAppStore } from '@/store/modules/app';
import { debounce } from 'lodash';

type SelectAccountType = {
  id: number | string;
  name: string;
  appId?: string;
  appName?: string;
  limit?: number;
  isCur?: boolean;
  instanceId?: string;
  assetId?: number;
};

const props = defineProps<{
  advertiserId: SelectAccountType[];
  type: string;
}>();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const appStore = useAppStore();

const emit = defineEmits(['getAppInfo']);

const dialog = reactive<DialogOption>({
  visible: false,
  title: '选择小程序'
});

const curType = ref(1);

const assetsList = ref<EventAssetsVo[]>([]);

const userList = ref<SelectAccountType[]>([]);

const keywords = ref('');

const loading = ref(false);

// const productList = ref<WechatMicroAppVO | ByteMicroAppVO>();

const productList = ref<any[]>([]);
const productListTemp = ref<any[]>([]);

// const selectRows = ref<any[]>([]); //考虑后期多帐号对应不同商品
const selectRows = ref<Array<any[]>>(Array.from({ length: props.advertiserId.length }, () => []));

const selectResult = ref<Array<SelectAccountType[]>>(Array.from({ length: props.advertiserId.length }, () => []));

const tableRef = ref(null);

const curAdvertiserId = computed(() => {
  return userList.value[curAdvertiserIndex.value].id || 0;
});

const curAdvertiserIndex = ref(0);

const total = ref(0);

const initFormQuery: MicroAppQuery = {
  pageNum: 1,
  pageSize: 10,
  accountId: appStore.accountId, //账号id
  advertiserId: null, //广告主ID
  searchKey: null
};

const queryParams = ref<MicroAppQuery>({ accountId: appStore.accountId, advertiserId: curAdvertiserId, ...initFormQuery });

const updateRow = (row) => {
  selectRows.value[curAdvertiserIndex.value] = [row];
  tableRef.value?.toggleRowSelection(row, true);
  if (curType.value === 1) {
    selectResult.value[curAdvertiserIndex.value] = [
      {
        id: curAdvertiserId.value,
        name: userList.value[curAdvertiserIndex.value].name,
        appId: props.type === 'WECHAT_APP' ? row.instanceId : row.appId,
        appName: row.name,
        instanceId: row.instanceId || '',
        assetId: assetsList.value.find((items) => items.microAppInstanceId === row.instanceId)?.assetId
      }
    ];
    userList.value[curAdvertiserIndex.value].appId = props.type === 'WECHAT_APP' ? row.instanceId : row.appId;
    userList.value[curAdvertiserIndex.value].appName = row.name;
    userList.value[curAdvertiserIndex.value].instanceId = row.instanceId || '';
    userList.value[curAdvertiserIndex.value].assetId = selectResult.value[curAdvertiserIndex.value][0].assetId;
  } else if (curType.value === 0) {
    userList.value.map((item, index) => {
      selectResult.value[index] = [
        {
          id: item.id,
          name: item.name,
          appId: props.type === 'WECHAT_APP' ? row.instanceId : row.appId,
          appName: row.name,
          instanceId: row.instanceId || '',
          assetId: assetsList.value.find((items) => items.microAppInstanceId === row.instanceId)?.assetId
        }
      ];
      userList.value[index].appId = props.type === 'WECHAT_APP' ? row.instanceId : row.appId;
      userList.value[index].appName = row.name;
      userList.value[index].instanceId = row.instanceId || '';
      userList.value[index].assetId = selectResult.value[curAdvertiserIndex.value][0].assetId;
    });
  }
};

const handelRowClick = (row) => {
  tableRef.value?.clearSelection();
  const checkRowIndex = selectRows.value[curAdvertiserIndex.value].findIndex((item) => item.instanceId === row.instanceId);
  if (checkRowIndex !== -1) {
    tableRef.value?.toggleRowSelection(row, false);
    selectRows.value.splice(checkRowIndex, 1);
    clearUserAppInfo();
  } else {
    updateRow(row);
  }
};

/**
 * 字节小程序切换全复用或按帐户分配
 */
const handleCurType = (i: number) => {
  curType.value = i;
};

/**
 * tabel选择切换
 */
const handleSelectionChange = (selection: WechatMircroAppItem[] | ByteMicroAppItem[]) => {
  if (selection.length || selectRows.value[curAdvertiserIndex.value].length) {
    const newSelection = selection.filter((item, index) => index === selection.length - 1);
    tableRef.value?.clearSelection();
    setTimeout(() => {
      newSelection.map((item) => {
        tableRef.value?.toggleRowSelection(item, true);
        updateRow(item);
      });
    }, 20);
  }
  if (selection.length === 0 || selectRows.value[curAdvertiserIndex.value].length === 0) {
    clearUserAppInfo();
    tableRef.value?.clearSelection();
  }
};
/**
 *  清除用户已选数据
 */
const clearUserAppInfo = () => {
  selectRows.value[curAdvertiserIndex.value] = [];
  selectResult.value[curAdvertiserIndex.value] = [];
  userList.value[curAdvertiserIndex.value].appId = null;
  userList.value[curAdvertiserIndex.value].appName = null;
  userList.value[curAdvertiserIndex.value].instanceId = null;
};
/**
 *  清除用户已选数据
 */
const clearAllUserAppInfo = () => {
  userList.value.map((item) => {
    item.appId = null;
    item.appName = null;
  });
};
/**
 *  切换用户
 */
const selectUser = (i: number) => {
  console.log('切换用户', i);
  if (curAdvertiserIndex.value === i) return;
  curAdvertiserIndex.value = i;
  getMircoAppList();
  if (props.type === 'BYTE_APP') {
    //请求资产列表
    getEventAllAssetsListInfo();
  }
};

/**
 * 搜索
 */
const search = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.searchKey = keywords.value;
  getMircoAppList();
};
/**
 *  条件搜索
 */
const searchQuery = () => {
  if (!keywords.value) {
    proxy?.$modal.msgError('请输入关键字');
    return;
  }
  search();
};
const toSearch = debounce(searchQuery, 300);
/**
 *  清空搜索
 */
const clearSearch = debounce(search, 300);

const submit = () => {
  let isComplete = true;

  if (props.type === 'BYTE_APP' && curType.value === 0) {
    if (!userList.value[0].appId) {
      proxy?.$modal.msgError('请选择小程序');
      return;
    }
    //字节小程序共用一个appId
    userList.value.map((item, index) => {
      if (index > 0) {
        item.appId = userList.value[0].appId;
        item.appName = userList.value[0].appName;
        item.instanceId = userList.value[0].instanceId;
      }
    });
  }
  if (curType.value === 1) {
    userList.value.map((item) => {
      if (!isComplete) return;
      isComplete = !item.appId ? false : true;
    });
    if (!isComplete) {
      proxy?.$modal.msgError('请为帐户选择小程序');
      return;
    }
  }
  console.log('userList======================>', userList.value);
  emit('getAppInfo', userList.value);
  hide();
};

watch(
  () => props.advertiserId.length,
  () => {
    nextTick(() => {
      setTimeout(() => {
        init();
      }, 200);
    });
  },
  { immediate: true }
);
// watch(
//   () => props.type,
//   (newVal) => {
//     dialog.title = props.type === 'WECHAT_APP' ? '选择微信小程序' : '选择字节小程序';
//     curType.value = 1;
//     console.log('22');
//     init();
//   }
// );

const init = () => {
  nextTick(() => {
    dialog.title = props.type === 'WECHAT_APP' ? '选择微信小程序' : '选择字节小程序';
    curType.value = 1;
    userList.value = JSON.parse(JSON.stringify(props.advertiserId));
    userList.value.map(async (item, index) => {
      if (curAdvertiserIndex.value === 0 && index === 0) {
        //请求小程序列表
        await getMircoAppList();
        if (props.type === 'BYTE_APP') {
          //请求资产列表
          await getEventAllAssetsListInfo();
        }
      }
    });
  });
};

const clearAll = () => {
  selectRows.value = Array.from({ length: props.advertiserId.length }, () => []);
  selectResult.value = Array.from({ length: props.advertiserId.length }, () => []);
  tableRef.value?.clearSelection();
  userList.value[curAdvertiserIndex.value].appId = null;
  userList.value[curAdvertiserIndex.value].appName = null;
};

const getEventAllAssetsListInfo = async () => {
  const res = await getEventAllAssetsList({ pageNum: 1, pageSize: 10, accountId: appStore.accountId, advertiserId: curAdvertiserId.value as number });
  assetsList.value = res.rows;
  console.log('========================>productList', productList.value);
  
  productList.value = productListTemp.value.filter((item) => {
    return assetsList.value.some((asset) => asset.microAppInstanceId === item.instanceId);
  });
  loading.value = false;
};

const getMircoAppList = async () => {
  loading.value = true;
  queryParams.value.advertiserId = curAdvertiserId.value as number;
  if (props.type !== 'AWEME') {
    if (props.type === 'WECHAT_APP') {
      queryParams.value.pageNum = 1;
      queryParams.value.pageSize = 100;
      const res = await getAllWechatApplet(queryParams.value);
      productListTemp.value = res.data;
    } else {
      queryParams.value.pageNum = 1;
      queryParams.value.pageSize = 100;
      const res = await queryToolsMicroAppNew(queryParams.value);
      productListTemp.value = res.data;
    }

    if (userList.value[curAdvertiserIndex.value].appId) {
      let inList = false;
      productListTemp.value.map((item) => {
        if (item.instanceId === userList.value[curAdvertiserIndex.value].instanceId) {
          inList = true;
          selectRows.value[curAdvertiserIndex.value] = item;
          setTimeout(() => {
            tableRef.value?.toggleRowSelection(item, true);
          }, 20);
        }
      });
      if (!inList) {
        userList.value[curAdvertiserIndex.value].appId = null;
        userList.value[curAdvertiserIndex.value].appName = null;
      }
    }
    if (props.type === 'WECHAT_APP') {
      productList.value = productListTemp.value;
      loading.value = false;
    }
  }
};

onMounted(() => {
  nextTick(() => {});
});

const show = () => {
  if (!props.advertiserId) return;
  dialog.visible = true;
};
const hide = () => {
  curAdvertiserIndex.value = 0;
  dialog.visible = false;
};

defineExpose({ show, hide, init, clearAll });
</script>

<style lang="scss" scoped>
::v-deep(.myTable) {
  thead {
    th:nth-child(1) {
      .cell {
        display: none;
      }
    }
  }
}
::v-deep(.pagination-container) {
  margin: 0 !important;
  height: auto;
}
::v-deep(.pagination-container .el-pagination) {
  float: unset;
}
::v-deep(.el-table--fit .el-table__inner-wrapper:before) {
  display: none;
}
.type {
  .items {
    &.active {
      background-color: #79bbff;
      color: #fff;
    }
  }
}
</style>
